package com.tg.base.concurrent.lock.reentrantReadWriteLock;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 读写锁基础示例
 */
public class ReentrantReadWriteLockTest {

    private static final Account account = new Account();

    private static final Random random = new Random();

    public static void main(String[] args) {
        incr();
        load();
    }

    private static void incr() {

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                Integer leftAmount = 0;
                try {
                    leftAmount = account.updateAmount(20);
                    System.out.println("充值20元");
                    TimeUnit.MILLISECONDS.sleep(50);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                } finally {
                    System.out.println("充值完成:" + leftAmount);
                }
            }

        }).start();
    }

    private static void load() {
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                for (int j = 0; j < 5; j++) {
                    System.out.println("查余额" + account.getAmount());
                    threadSleep(100);
                }
            }).start();
        }
    }


    private static void threadSleep(int boundary) {
        try {
            Integer i = random.nextInt(boundary);
            TimeUnit.MILLISECONDS.sleep(i.longValue());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
